import axios from "axios";
import httpCode from "./httpCode";

const service = axios.create({
  baseURL: "",
  timeout: 10 * 1000, // 设置10秒后请求超时
  headers: {
    "Content-Type": "application/json;charset=utf-8",
  }, // 设置默认请求头部
});

service.interceptors.request.use(
  (config) => {
    return config;
  },
  (error) => {
    return Promise.reject(error);
  },
);

service.interceptors.response.use(
  (response) => {
    // 若未返回状态码则默认设置失败状态
    const code = response.data.code || "default";
    if (code === 200) {
      return response.data;
    } else {
      const msg = response.data.msg || httpCode[code];
      return Promise.reject(msg || "error");
    }
  },
  (error) => {
    let msg = error.message;
    const code = error?.response?.status || "default";
    if (msg == "Network Error") {
      msg = "网络异常";
    } else if (msg.includes("timeout")) {
      msg = "请求超时，请重试";
    } else if (msg.includes("Request failed with status code")) {
      msg = error?.response?.data?.message || httpCode[code] || "系统接口" + msg.substr(msg.length - 3) + "异常";
    }
    return Promise.reject(msg);
  },
);

export default service;
